﻿using StandardManager.DB;
using StandardManager.DBItems;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace StandardManager.Controls
{
    public partial class PageContentControl : UserControl
    {
        public PictureBox pictureBox { get; set; }
        private BookContents m_currentSelBookContent;

        public PageContentControl()
        {
            InitializeComponent();
        }

        #region 初始内容
        public void SetContent(string searchText)
        {
            m_enableHighlightText = false;
            this.textBoxMatchItem.Text = searchText;
        }

        public void EndSetContent()
        {
            m_enableHighlightText = true;
        }
        #endregion

        private bool m_enableHighlightText = true;
        private void textBoxMatchItem_TextChanged(object sender, EventArgs e)
        {
            if (m_enableHighlightText == false)
            {
                return;
            }
            HighlightText(this.textBoxMatchItem.Text);
        }

        public void ShowSearchBook(BookContents selBoox)
        {
            m_currentSelBookContent = selBoox;

            this.richTextBox1.Text = selBoox.BookContent;
            this.pictureBox.BackgroundImage = Image.FromStream(new MemoryStream(selBoox.BookImg));
            this.pictureBox.BackgroundImageLayout = ImageLayout.Stretch;

            HighlightText(this.textBoxMatchItem.Text);
        }

        private void HighlightText(string textToHighlight)
        {
            int startIndex = 0;

            // 清除之前的高亮  
            richTextBox1.SelectAll();
            richTextBox1.SelectionBackColor = Color.White; // 恢复背景色  

            // 查找并高亮指定文字  
            while ((startIndex = richTextBox1.Find(textToHighlight, startIndex, RichTextBoxFinds.None)) != -1)
            {
                richTextBox1.Select(startIndex, textToHighlight.Length);
                richTextBox1.SelectionBackColor = Color.Yellow; // 设置高亮颜色  
                startIndex += textToHighlight.Length; // 移动起始索引  
            }

            richTextBox1.DeselectAll(); // 取消选择  
        }

        #region 保存信息
        private void toolStripButton1_Click(object sender, EventArgs e)
        {
            m_currentSelBookContent.BookContent = this.richTextBox1.Text;
            ConnectionDatabase_S2 connectionDatabase_S2 = ConnectionDatabase_S2.BuildSqliteConnection(GlobalConfig.Instance.DBFileName);
            var booksSql = m_currentSelBookContent.BuildUpdateContentSql();
            connectionDatabase_S2.ExecuteSQL(booksSql);
            connectionDatabase_S2.Dispose();

            MessageBox.Show("保存成功");
        }

       
        #endregion


    }
}
